//
//  RTCController.m
//  HollySdk
//
//  Created by hollycrm on 2021/3/4.
//

#import "RTCController.h"
#import <AVFoundation/AVFoundation.h>
#import "OneToOneViewController.h"
#import "Request.h"
@interface RTCController(){
    TRTCCloud *trtcCloud;
}
@property (nonatomic,weak) id<TRTCDelegate> rtcviewdelegate;
@end

@implementation RTCController

+ (instancetype)shareController{
    static RTCController * con = nil;
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        con = [[super allocWithZone:NULL] init];
        con.isMute = false;
        con.isSpeakerOn = true;
        con.isFrontCamera = [[[TRTCCloud sharedInstance] getDeviceManager] isFrontCamera];
        con.rtcCallType = pointToPointVideo;
    });
    return con;
}

+ (id)allocWithZone:(struct _NSZone *)zone{
    return [self shareController];
}



#pragma mark trtc 代理
-(void)onError:(TXLiteAVError)errCode errMsg:(NSString *)errMsg extInfo:(NSDictionary *)extInfo{
    NSLog(@"error*******%@",errMsg);
    if (errCode == ERR_ROOM_ENTER_FAIL) {
        //[self reportA6TrtcStatus:2];
        if(self.rtcviewdelegate != nil){
            [_rtcviewdelegate onError:errMsg];
        }
        
        [self exitRoom];
        return;
    }
}

- (void)onUserVideoAvailable:(NSString *)userId available:(BOOL)available{
    if(self.rtcviewdelegate != nil){
        [self.rtcviewdelegate onUserVideoAvailable:userId available:available];
    }
}

-(void)reportExitRoom{
    Request *req = [[Request alloc] init];
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    [param setObject:@"MeetRoom" forKey:@"Modual"];
    [param setObject:@"videoExitRoom" forKey:@"Action"];
    [param setObject:_touserid forKey:@"VisitorId"];
    [param setObject:[SDKManager shareManager].account forKey:@"Account"];
    [req post:param withUrl:requestUrl succ:^(NSDictionary * _Nonnull dic) {
        
    } fail:^(NSString * _Nonnull msg) {
        
    }];
}

- (void)onEnterRoom:(NSInteger)result{
   
//    [self reportA6TrtcStatus:1];
    NSLog(@"Enter Room *******");
    self.inRoom = true;
    [[UIApplication sharedApplication] setIdleTimerDisabled:true];
}

- (void)onSendFirstLocalAudioFrame{
    
}

- (void)onRemoteUserEnterRoom:(NSString *)userId{
    NSLog(@"userEnter---%@",userId);
    self.rtcCallState = incall;
    if (self.rtcviewdelegate != nil){
        [self.rtcviewdelegate onUserEnter:userId];
    }
}



- (void)onRemoteUserLeaveRoom:(NSString *)userId reason:(NSInteger)reason{
    
    NSLog(@"userLeave---%@",userId);
    self.rtcCallState = leave;
    [self exitRoom];
    if (self.rtcviewdelegate != nil){
        [self.rtcviewdelegate onUserLeave:userId];
    }
}


- (void)onMicDidReady{
    
}



- (void)onFirstAudioFrame:(NSString *)userId{
    
}

-(void)onExitRoom:(NSInteger)reason{
    //NSString *msg = [NSString stringWithFormat:@"离开房间[%d]: reason[%d]", roomID, reason];
    self.rtcCallState = leave;
    self.inRoom = false;
    [[UIApplication sharedApplication] setIdleTimerDisabled:false];
}

#pragma mark 通话相关操作
-(void)setIsMute:(BOOL)isMute{
    _isMute = isMute;
    [trtcCloud muteLocalAudio:isMute];
}
-(void)setIsSpeakerOn:(BOOL)isSpeakerOn{
    _isSpeakerOn = isSpeakerOn;
    if (_isSpeakerOn) {
        [trtcCloud setAudioRoute:TRTCAudioModeSpeakerphone];
    }
    else {
        [trtcCloud setAudioRoute:TRTCAudioModeEarpiece];
    }
}

-(void)pushView{
    OneToOneViewController *vc = [[OneToOneViewController alloc] init];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    self.rtcviewdelegate = vc;
    UIViewController * rootCon = [UIApplication sharedApplication].keyWindow.rootViewController;
    if (rootCon != nil) {
        [rootCon presentViewController:vc animated:true completion:nil];
    }
}

-(void)enterRoomWithView:(BOOL)pushView
{
    [self checkVideoSession];
    
    if (pushView) {
        [self pushView];
    }

    trtcCloud = [TRTCCloud sharedInstance];
    trtcCloud.delegate = self;
    if(self.inRoom){
        [trtcCloud exitRoom];
    }
    //TRTCParams 定义参考头文件TRTCCloudDef.h
    TRTCParams *params = [[TRTCParams alloc] init];
    params.sdkAppId    = self.sdkAppId;
    params.userId      = self.userId;
    params.userSig     = self.userSig;
    params.roomId = self.roomId;
    
    [TRTCCloud setConsoleEnabled:false]; //停止控制台输出。。。太多了活结
    [trtcCloud enterRoom:params appScene:TRTCAppSceneVideoCall];
    //[trtcCloud enterRoom:params appScene:TRTCAppSceneAudioCall];
    [trtcCloud startLocalAudio:TRTCAudioQualitySpeech];
    [trtcCloud muteLocalAudio:false];
    [trtcCloud setAudioRoute:true];
    [trtcCloud enableAudioVolumeEvaluation:300];
    [trtcCloud setAudioRoute:TRTCAudioModeSpeakerphone];
}

-(void)exitRoom{
    [self reportExitRoom];
    trtcCloud = [TRTCCloud sharedInstance];
    [trtcCloud exitRoom];
    [trtcCloud stopLocalAudio];
    [trtcCloud stopLocalPreview];
    trtcCloud = nil;
}

-(void)checkVideoSession{
    
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        if (!granted) {//不允许
            dispatch_async(dispatch_get_main_queue(), ^{
                
                UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"提示" message:@"摄像头不可用，请在系统“设置-隐私-相机”的权限管理中，允许[小秘]访问相机" preferredStyle: UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [ac addAction:action];
                
            });
        }else{//开启
            
        }
    }];
}


@end
